package com.situ.skymallimageapi.service.impl;

import com.situ.service.ImageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Service
public class ImageServiceImpl implements ImageService {
    //上传本地路径
    @Value("${upload.location}")
    private String uploadLocation;

    //访问前缀
    @Value("${upload.url-prefix}")
    private String urlPrefix;


/*    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }*/


    /**
     * 上传图片
     * @param file 文件
     * @return 图片路径
     */
    @Override
    public String upload(MultipartFile file, String type) {
        File dir = new File(uploadLocation + "/images/" + type);
        if (!dir.exists()) {
            boolean b = dir.mkdirs();
            if (!b) {
                throw new RuntimeException("创建目录失败");
            }
        }

        String fileName = file.getOriginalFilename();//上传文件名
        assert fileName != null;
        int idx = fileName.lastIndexOf(".");

        //文件扩展名，包括点
        String ext = fileName.substring(idx);
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));

        //追加3位随机数
        Random random = new Random();
        int num = random.nextInt(1000);
        fileName = fileName + "-" + num + ext;

        try {
            File target = new File(dir.getCanonicalPath() + "/" + fileName);
            file.transferTo(target);//传输文件

            if (urlPrefix.endsWith("/")) {
                urlPrefix = urlPrefix.substring(0, urlPrefix.length() - 1);
            }

            String url = urlPrefix + "/images/" + type + "/" + fileName;

            //定时删除任务
            /*scheduledExecutorService.schedule(() -> {
                if (!redisTemplate.hasKey(url)) {
                    boolean b = target.delete();//删除文件
                    if (!b) {
                        throw new UnsupportedOperationException("图片删除失败");
                    }
                }
            }, 3, TimeUnit.MINUTES);*/

            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
